<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!--  总工授权管理 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      class="updateGeneralAuthorization"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :is-emit="false"
            :editModel="editModel == 0 ? '' : ''"
          >
          </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="相关资料上传"></title-name>
          <custom-form
            :formList="formListDataUpload"
            :form="form"
            :is-emit="false" 
            :editModel="editModel == 0 ? '' : ''"
          >
            <template v-slot:table>
              <a-form-model-item
                class="mb20"
                label=" "
                :colon="false"
              >
                <a-table
                  ref="formTable"
                  class="updateTotalPriceApproval-table"
                  bordered
                  :columns="columns"
                  :data-source="form.fileListArr"
                  :pagination="false"
                >
                  <span
                    slot="serial"
                    slot-scope="text, record, index"
                  >{{ index + 1 }}</span>
                  <template
                    v-for="col in ['fileListName', 'fileList']"
                    :slot="col"
                    slot-scope="text, record"
                  >
                    <div
                      :key="col"
                      class="form-item"
                    >
                      <template>
                        <div v-if="col === 'fileList'">
                          <template v-if="editModel != 0">
                            <l-table
                              businessCode="FACE15"
                              :uploadArrys.sync="record[col]"
                            ></l-table>
                          </template>
                          <file-link
                            v-else
                            :fileList="record[col]"
                            style="margin-top: -3px"
                          ></file-link>
                        </div>
                        <span v-else>{{record[col]}}</span>
                      </template>

                    </div>
                  </template>
                </a-table>
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
     
    <!-- 页脚操作栏 -->
    <div
      class="btn_box page-btn-right-top"
      v-if="editModel != 0 && !isConsultation"
    >
      <a-button
        class="button_right"
        v-if="form.status == 'REJECTED'"
        type="primary"
        :loading="loadingBtn.REJECTED"
        @click="handleSubmit('REJECTED')"
      >保存</a-button>
      <span v-else>
        <a-button
          v-if="this.editModel != 3"
          class="button_right"
          type="primary"
          :loading="loadingBtn.DRAFT"
          @click="handleSubmit('DRAFT')"
        >保存草稿</a-button>
      </span>
      <a-button
        class="button_right"
        type="primary"
        :loading="loadingBtn.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
      >提交</a-button>
      <a-button @click="handleActiveClose">关闭</a-button>
    </div>
    <div
      class="btn_box page-btn-right-top"
      v-else-if="!isConsultation"
    >
      <a-button @click="handleActiveClose">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { addGeneral, getGeneralDetail } from '@/api/technical/general'
import { getProjectsList } from '@/api/projects'
import { getProjectsDel } from '@/api/project/projects'
import { list } from '@/api/technical/config'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import { getAllBranchCompany } from '@/api/commons'
import { undertake } from './model'
const columns = [
  { title: '序号', dataIndex: 'serial', width: 65, scopedSlots: { customRender: 'serial' } },
  { title: '文件名称', dataIndex: 'fileListName', align: 'left', scopedSlots: { customRender: 'fileListName' }, ellipsis: true, width: 500 },
  { title: '文件', dataIndex: 'fileList', align: 'center', scopedSlots: { customRender: 'fileList' } }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople
  },
  data() {
    this.columns = columns
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增;
      querCompany: [],
      form: {
        fileListArr: [
          { fileListName: '申请报告（需加盖公司科技部印章）', fileList: [] },
          { fileListName: '工程概况（包括文字简介、工程效果图、现场形象进度照片）', fileList: [] },
          { fileListName: '授权委托书（需在项目名称后括号备注工程地点）', fileList: [] },
          { fileListName: '项目班子成员任命文件', fileList: [] },
          { fileListName: '被授权人个人简历', fileList: [] },
          { fileListName: '现场情况报告', fileList: [] },
          { fileListName: '施组报审的公司审批表扫描件', fileList: [] },
          { fileListName: '总承包合同封面及最后盖章页扫描件', fileList: [] },
          { fileListName: '其他', fileList: [] }
        ]
      }, // 表单
      findCountQueryParam: {
        pageNo: 1,
        pageSize: 10000,
        query: {}
      },
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false,
        FILE: false
      },
      rules: {
        undertakeId: [{ required: true, message: '请选择承接名义' }],
        projectTypeId: [{ required: true, message: '请选择项目类型' }],
        branchComId: [{ required: true, message: '请选择实施单位' }],
        projectId: [{ required: true, message: '请选择项目名称' }],
        authorizer: [{ required: true, message: '请输入授权人', trigger: 'blur' }],
        authorizationCode: [{ required: true, message: '请输入授权书编号', trigger: 'blur' }],
        bearAuthorizer: [{ required: true, message: '请输入被授权人', trigger: 'blur' }],
        applicantId: [{ required: true, message: '请选择申请人' }],
        authorizationDate: [{ required: true, message: '请选择授权申请日期' }]
      }, // 校验规则
      init: false, // 初始化控件
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  created() {},
  async mounted() {
    this.querCompanyFn()
    this.$route.meta.title = ['总工授权管理  查看', '总工授权管理  编辑', '总工授权管理  新增'][this.editModel]
    if (this.editModel != 2) {
      await this.getDetailData()
    } else {
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
        this.form.fillName = this.$userInfo().name
        this.init = true
      })
    }
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technical_chief_engineer_auth')
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'undertakeId',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '承接名义',
          data: undertake,
          change: (e) => {
            let undertake = e * 1 === 0 ? '局名义承接' : e * 1 === 1 ? '股份公司名义承接' : ''
            this.$set(this.form, 'undertake', undertake)
          }
        },
        {
          keyName: 'projectTypeId',
          type: BSelect,
          disabled: this.editModel == 0,
          label: '项目类型',
          attrs: {
            form: this.form,
            request: this.getProjectTypeList
          },
          selectChange: (e) => {
            this.$set(this.form, 'projectType', e?.name)
          }
        },
        {
          keyName: 'authorizationCode',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '授权书编号'
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '实施单位',
        //   placeholder: '请选择',
        //   disabled: this.editModel == 0,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        {
          type: 'a-select',
          keyName: 'branchComId',
          label: '实施单位',
          data: this.querCompany,
          placeholder: '请选择实施单位',
          disabled: this.editModel == 0,
          replaceFields: {
            label: 'name',
            value: 'id'
          },
          change: (e) => {
            console.log(e)
          }
        },
        {
          type: SelectProject,
          keyName: 'projectId',
          viewName: 'projectName',
          disabled: this.editModel == 0,
          placeholder: '请选择所属项目名称',
          label: '项目名称',
          attrs: {
            autoSelected: this.editModel == 2,
            keyValue: 'branchComId',
            isClear: this.editModel == 2,
            isEdit: this.editModel != 2,
            isSelf: false,
            form: this.form
          },
          selectChange: (e) => {
            this.getProjectsListFn(e.name)
          }
        },
        {
          keyName: 'structureType',
          type: 'a-input',
          disabled: true,
          label: '结构类型',
          placeholder: '自动带出'
        },
        {
          keyName: 'projectPlace',
          type: 'a-input',
          disabled: true,
          label: '工程地点',
          placeholder: '自动带出',
          span: 24
        },
        {
          keyName: 'scale',
          type: 'a-input',
          disabled: true,
          label: '规模(面积、里程)',
          placeholder: '自动带出'
        },
        {
          keyName: 'startDate',
          type: 'a-input',
          disabled: true,
          label: '开工日期(合同约定)',
          placeholder: '自动带出'
        },
        {
          keyName: 'completionDate',
          type: 'a-input',
          disabled: true,
          label: '竣工日期(合同约定)',
          placeholder: '自动带出'
        },
        {
          keyName: 'authorizer',
          type: 'a-input',
          disabled: this.editModel == 0,
          label: '授权人',
          placeholder: '请输入'
        },
        {
          keyName: 'bearAuthorizer',
          type: 'a-input',
          disabled: this.editModel == 0,
          label: '被授权人',
          placeholder: '请输入'
        },
        {
          type: ASelectOrgPeople,
          keyName: 'applicantId',
          label: '申请人',
          placeholder: '请选择',
          disabled: this.editModel == 0,
          onSelectChange: (e) => {
            this.$set(this.form, 'applicant', e?.name)
          }
        },
        {
          keyName: 'authorizationDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '授权申请日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    },
    formListDataUpload() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    }
  },
  methods: {
    querCompanyFn() {
      return getAllBranchCompany({ tagCodes: ['BC'] }).then((res) => {
        this.querCompany = res.data
      })
    },
    //获取分包商下面的合同
    async getProjectTypeList() {
      let queryParam = { pageNo: 1, pageSize: 10, type: 14 }
      let filterData = [] //过滤不可用的数据
      return list(queryParam)
        .then((res) => {
          if (res.data?.length > 0) {
            filterData = res.data.filter((item) => item.enabled)
          }
          return { code: 200, data: filterData }
        })
        .catch(() => {
          return { code: 200, data: [] }
        })
    },
    async getProjectsListFn(e) {
      let projectId = this.form.projectId || null
      if (projectId) {
        let detailData = await getProjectsDel({ projectId: projectId })
        if (detailData.code == '200') {
          let reqData = detailData.data
          this.$set(this.form, 'structureType', reqData.structureTypeName)
          this.$set(this.form, 'projectPlace', reqData.projectAddress)
          this.$set(this.form, 'scale', reqData.contractTotalArea || reqData.contractMileage)
          this.$set(this.form, 'startDate', reqData.contractStartDate)
          this.$set(this.form, 'completionDate', reqData.contractEndDate)
        } else {
          this.$message.warning(detailData.message)
        }
      } else {
        this.form.structureType = null
        this.form.projectPlace = null
        this.form.scale = null
        this.form.startDate = null
        this.form.completionDate = null
      }
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getGeneralDetail({ id: this.id })
          .then((res) => {
            this.loading = false
            res.data.projectId = res.data.projectId.toString()
            this.form = { ...this.form, ...res.data }
            let form = this.form,
              fileListArr = form.fileListArr
            fileListArr[0].fileList = form.applyFile || []
            fileListArr[1].fileList = form.projectInfoFile || []
            fileListArr[2].fileList = form.authorizationFile || []
            fileListArr[3].fileList = form.appointmentFile || []
            fileListArr[4].fileList = form.authorizerResumeFile || []
            fileListArr[5].fileList = form.onSiteFile || []
            fileListArr[6].fileList = form.subAuditFile || []
            fileListArr[7].fileList = form.contractStampFile || []
            fileListArr[8].fileList = form.otherFile || []
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * @description: 保存草稿校验
     * @return {boolean}
     */
    validateDraftForm() {
      let pass = false
      this.$refs.ruleForm.validateField(['branchComId', 'projectId'], (e) => {
        pass = !e
      })
      return pass
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      let isHaveFile = this.form.fileListArr.some(v=>{
        if(v.fileListName!='其他'){
          return v.fileList?.length === 0
        }
      })
      if ( status == 'SUBMITTED' && isHaveFile){
        this.$message.warning('相关资料为必填项')
        return false
      }
      // 保存草稿将实施单位和项目名称作为必传项
      if (status === 'DRAFT' && !this.validateDraftForm()) return
      let form = this.$clone(this.form),
        fileListArr = form.fileListArr
       
      form.applyFile = fileListArr[0].fileList
      form.projectInfoFile = fileListArr[1].fileList
      form.authorizationFile = fileListArr[2].fileList
      form.appointmentFile = fileListArr[3].fileList
      form.authorizerResumeFile = fileListArr[4].fileList
      form.onSiteFile = fileListArr[5].fileList
      form.subAuditFile = fileListArr[6].fileList
      form.contractStampFile = fileListArr[7].fileList
      form.otherFile = fileListArr[8].fileList
      this.loading = true
      this.loadingBtn[status] = true
      if (status != 'REJECTED') {
        form.status = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.status = 5
      }
      let api = addGeneral
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig:6,(flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
              return
            }else{
            this.$multiTab.close()
          }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })

      })
    }
  }
}
</script>
<style lang="less" scoped>
.updateGeneralAuthorization .ant-btn {
  height: 30px;
}
</style>
